<template>
  <div class="page-container">
    <!-- 左边试卷部分 -->
    <div class="test-paper-container">
      <!-- 试卷头部信息 -->
      <div class="paper-header">
        <!-- <h1 class="paper-title">{{ testTitle }} / {{ examScore }}</h1> -->
        <h1 class="paper-title">{{ testTitle }}</h1>
        <div class="paper-meta">
          <div class="meta-item">
            <span class="meta-label">学科：</span>
            <span class="meta-value">{{ Subject }}</span>
          </div>

          <div class="meta-item">
            <span class="meta-label">时间：</span>
            <span class="meta-value">{{ examTime }}分钟</span>
          </div>

          <div class="meta-item">
            <span class="meta-label">总分：</span>
            <span class="meta-value">{{ examScore }}分</span>
            <span v-if="showResult" class="total-score">得分：<span class="score-value">{{ paperStore.calculateTotalScore()
                }}</span>分</span>
          </div>
        </div>
      </div>

      <!-- 题型统计 -->
      <!-- <div class="exercise-stats">
        <div class="stats-card">
          <div class="stats-content">
            <div class="stat-item">
              <span class="stat-label">选择题：</span>
              <span class="stat-value">{{ choiceCount }}题</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">填空题：</span>
              <span class="stat-value">{{ fillCount }}题</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">判断题：</span>
              <span class="stat-value">{{ judgeCount }}题</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">简答题：</span>
              <span class="stat-value">{{ shortAnswerCount }}题</span>
            </div>
          </div>
        </div>
      </div> -->

      <!-- 题目列表 -->
      <div class="exercises-list">
        <div v-for="(exercise, index) in exercises" :key="exercise.exercisesId" class="exercise-item">
          <div class="exercise-card">
            <div class="exercise-content">
              <!-- 题目序号和标题 -->
              <div class="exercise-title">
                <span class="exercise-number">{{ index + 1 }}.</span>
                <span class="exercise-text">{{ exercise.title }}</span>
                <span class="exercise-total-score">
                  ({{ calculateTotalScore(exercise.questions) }}分)
                </span>
              </div>

              <!-- 按题型分组显示 -->
              <div class="questions-by-type">
                <!-- 选择题 -->
                <div v-if="hasQuestionsOfType(exercise.questions, '选择题')" class="question-type-section">
                  <h3 class="question-type-title">选择题</h3>
                  <div v-for="question in filterQuestionsByType(exercise.questions, '选择题')" :key="question.recId">
                    <div class="question-title">
                      <div class="question-order">({{ question.displayOrder }})</div>
                      <div class="question-texts" v-html="question.questionTitle || null"></div>
                      <span class="question-score">({{ question.score }}分)</span>
                    </div>
                    <div class="exercise-options">
                      <div class="options-group">
                        <div v-for="(option, optIndex) in getOptions(exercise.exercisesId, question.recId)"
                          :key="optIndex" class="option-item">
                          <input type="radio" :name="`q-${exercise.exercisesId}-${question.recId}`"
                            :id="'q' + exercise.exercisesId + '-' + optIndex"
                            :checked="getAnswer(exercise.exercisesId, question.recId) === String.fromCharCode(65 + optIndex)"
                            @change="setAnswer(exercise.exercisesId, question.recId, ($event.target as HTMLInputElement).value)"
                            :value="String.fromCharCode(65 + optIndex)" class="option-radio">
                          <label>
                            <span class="option-letter">{{ String.fromCharCode(65 + optIndex) }}.</span>
                            <span>{{ option.content }}</span>
                          </label>
                        </div>
                      </div>
                    </div>
                    <!-- 答案和解析（提交后显示） -->
                    <div v-if="showResult" class="exercise-result">
                      <!-- 显示答案正确性 -->
                      <div
                        :class="isAnswerCorrect(exercise.exercisesId, question.recId, question.answer) ? 'correct' : 'wrong'">
                        {{ isAnswerCorrect(exercise.exercisesId, question.recId, question.answer) ? '正确' : '错误' }}
                      </div>
                      <div class="exercise-result-answer">
                        <span class="exercise-result-label">正确答案: </span>
                        <div class="exercise-result-answer-text" v-html="question.answer"></div>
                      </div>
                      <div>得分: {{ isAnswerCorrect(exercise.exercisesId, question.recId, question.answer) ?
                        question.score : 0 }}</div>
                      <div class="questionContentsAnalysis">
                        解析: <div v-html="question.analysis"></div>
                      </div>
                    </div>
                  </div>
                </div>

                <!-- 填空题 -->
                <div v-if="hasQuestionsOfType(exercise.questions, '填空题')" class="question-type-section">
                  <h3 class="question-type-title">填空题</h3>
                  <div v-for="question in filterQuestionsByType(exercise.questions, '填空题')" :key="question.recId">
                    <div class="question-title">
                      <div class="question-order">({{ question.displayOrder }})</div>
                      <div class="question-texts" v-html="question.questionTitle || null"></div>
                      <span class="question-score">({{ question.score }}分)</span>
                    </div>
                    <div class="exercise-fill">
                      <input type="text" class="fill-input" :value="getAnswer(exercise.exercisesId, question.recId)"
                        @input="setAnswer(exercise.exercisesId, question.recId, ($event.target as HTMLInputElement).value)"
                        placeholder="请输入答案" aria-label="填空题答案输入框">
                    </div>
                    <!-- 答案和解析（提交后显示） -->
                    <div v-if="showResult" class="exercise-result">
                      <!-- 同上，省略重复代码 -->
                    </div>
                  </div>
                </div>

                <!-- 判断题 -->
                <div v-if="hasQuestionsOfType(exercise.questions, '判断题')" class="question-type-section">
                  <h3 class="question-type-title">判断题</h3>
                  <div v-for="question in filterQuestionsByType(exercise.questions, '判断题')" :key="question.recId">
                    <div class="question-title">
                      <div class="question-order">({{ question.displayOrder }})</div>
                      <div class="question-texts" v-html="question.questionTitle || null"></div>
                      <span class="question-score">({{ question.score }}分)</span>
                    </div>
                    <div class="exercise-judge">
                      <label>
                        <input type="radio" :name="`q-${exercise.exercisesId}-${question.recId}`" value="正确"
                          :checked="getAnswer(exercise.exercisesId, question.recId) === '正确'"
                          @change="setAnswer(exercise.exercisesId, question.recId, '正确')">
                        正确
                      </label>
                      <label>
                        <input type="radio" :name="`q-${exercise.exercisesId}-${question.recId}`" value="错误"
                          :checked="getAnswer(exercise.exercisesId, question.recId) === '错误'"
                          @change="setAnswer(exercise.exercisesId, question.recId, '错误')">
                        错误
                      </label>
                    </div>
                    <!-- 答案和解析（提交后显示） -->
                    <div v-if="showResult" class="exercise-result">
                      <!-- 同上，省略重复代码 -->
                    </div>
                  </div>
                </div>

                <!-- 简答题 -->
                <div v-if="hasQuestionsOfType(exercise.questions, '简答题')" class="question-type-section">
                  <h3 class="question-type-title">简答题</h3>
                  <div v-for="question in filterQuestionsByType(exercise.questions, '简答题')" :key="question.recId">
                    <div class="question-title">
                      <div class="question-order">({{ question.displayOrder }})</div>
                      <div class="question-texts" v-html="question.questionTitle || null"></div>
                      <span class="question-score">({{ question.score }}分)</span>
                    </div>
                    <div class="exercise-short-answer">
                      <textarea :value="getAnswer(exercise.exercisesId, question.recId)"
                        @input="setAnswer(exercise.exercisesId, question.recId, ($event.target as HTMLInputElement).value)"
                        placeholder="请输入您的答案..." class="answer-textarea"></textarea>
                    </div>
                    <!-- 答案和解析（提交后显示） -->
                    <div v-if="showResult" class="exercise-result">
                      <!-- 同上，省略重复代码 -->
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>


      <!-- 操作按钮 -->
      <!-- <div class="action-buttons">
        <button class="save-btn" @click="handleSave">保存试卷</button>
        <button class="submit-btn" @click="handleSubmit">提交试卷</button>
      </div> -->
    </div>

    <!-- 右边试卷操作部分 -->
    <div class="left-container">
      <!-- 操作按钮区域 -->
      <div class="action-buttons">
        <!-- <button class="action-btn">下载试卷</button> -->
        <!-- <button class="action-btn">分值设置</button>
        <button class="action-btn">下载答题卡</button>
        <button class="action-btn">试卷分析</button> -->
        <!-- <button class="action-btn">保存试卷</button>
        <button class="action-btn">清空试卷</button> -->
        <button class="save-btn" @click="handleSave">保存试卷</button>
        <button class="submit-btn" @click="handleSubmit">提交试卷</button>
      </div>
      <!-- 试题统计 -->
      <!-- <div class="stats-section">
        <div class="section-title">试题统计(数量：)</div>
        <div class="stats-info">
          <span>题型统计：3</span>
          <span class="stats-divider">|</span>
          <span>平均难度：容易</span>
        </div> -->

      <!-- 题型统计详情 -->
      <!-- <div class="exercise-type-stats">
          <div class="type-item">
            <div class="type-header">
              <span>选择题</span>
              <span class="type-count">数量：4</span>
              <span class="type-percent">占比：66.67%</span>
            </div>
            <div class="exercise-numbers">
              <span>1</span>
              <span>2</span>
              <span>3</span>
              <span>4</span>
            </div>
          </div> -->

      <!-- <div class="type-item">
            <div class="type-header">
              <span>判断题</span>
              <span class="type-count">数量：7</span>
              <span class="type-percent">占比：76.67%</span>
            </div>
            <div class="exercise-numbers">
              <span>5</span>
            </div>
          </div>

          <div class="type-item">
            <div class="type-header">
              <span>问答题</span>
              <span class="type-count">数量：7</span>
              <span class="type-percent">占比：76.67%</span>
            </div>
          </div>
        </div>
      </div> -->
    </div>
  </div>
</template>

<script setup lang="ts">
import { usePaperStore } from '@/store/modules/questionBank/testpaperData'
import { Question } from '@/types/Course'
import { ElMessage } from 'element-plus'
import { computed, ref } from 'vue'

const showResult = ref(false)
const paperStore = usePaperStore()
// 使用计算属性获取试卷数据
const testTitle = computed(() => paperStore.currentPaper?.testTitle || '')
const Subject = computed(() => paperStore.currentPaper?.Subject || '')
const examTime = computed(() => paperStore.currentPaper?.examTime || 0)
const examScore = computed(() => paperStore.currentPaper?.examScore || 0)
const exercises = computed(() => paperStore.currentPaper?.exercises || [])


// 检查是否有指定题型的题目
const hasQuestionsOfType = (questions: Question[], type: Question['questionType']) => {
  return questions.some(q => q.questionType === type)
}

// 过滤出指定题型的题目
const filterQuestionsByType = (questions: Question[], type: Question['questionType']) => {
  return questions.filter(q => q.questionType === type)
}
// 获取解析后的选项
const getOptions = (exerciseId, questionId) => {
  return paperStore.getParsedOptions(exerciseId, questionId)
}
//  计算总分
const  calculateTotalScore = (questions) => {
  return questions.reduce((total, q) => total + (q.score || 0), 0);
}
// 获取/设置用户答案
const getAnswer = (exerciseId: number, questionId: number) => {
  return paperStore.userAnswers[exerciseId]?.[questionId] || ''
}

// 设置用户答案
const setAnswer = (exerciseId: number, questionId: number, answer: string) => {
  paperStore.setUserAnswer(exerciseId, questionId, answer)
}

// 判断单个问题是否正确
const isAnswerCorrect = (exerciseId: number, questionId: number, correctAnswer: string) => {
  return paperStore.isAnswerCorrect(exerciseId, questionId, correctAnswer)
}

// 计算总分
const totalScore = computed(() => paperStore.calculateTotalScore())

const handleSave = () => {
  // alert('试卷保存成功')
  ElMessage.success('试卷保存成功');
  emit('save')
}

const handleSubmit = () => {
  showResult.value = true
  // alert(`试卷提交成功，您的得分: ${totalScore.value}`)
  ElMessage.success(`试卷提交成功，您的得分: ${totalScore.value}`);
  emit('submit')
}

const emit = defineEmits<{
  (e: 'save'): void
  (e: 'submit'): void
}>()
</script>

<style scoped>
/* 页面容器 */
.page-container {
  width: var(--width);
  height: 100%;
  padding: 20px 0px;
  display: flex;
  font-family: "SimHei", "Microsoft YaHei", sans-serif;
  background-color: #f5f5f5;
}

/* 试卷容器（左侧） */
.test-paper-container {
  background-color: #fff;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  flex: 1;
  margin: 0px 20px;
  border: 1px solid #ddd;
  padding: 20px;
  overflow: auto;
}

.settings-image {
  max-width: 100%;
  height: auto;
  border: 1px solid #eee;
}

/* 试卷头部 */
.paper-header {
  text-align: center;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 2px solid #333;
}

.paper-title {
  font-size: 28px;
  color: #333;
  margin-bottom: 15px;
  /* font-weight: ; */
}

.paper-meta {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 20px 40px;
  font-size: 15px;
  color: #555;
}

.meta-item {
  display: flex;
  align-items: center;
}

.meta-label {
  font-weight: bold;
  color: #333;
}

.meta-value {
  margin-left: 5px;
}

.total-score {
  margin-left: 15px;
  font-weight: bold;
}

.score-value {
  color: #f56c6c;
}

/* 题型标题样式 */
.question-type-title {
  margin: 16px 0 8px 0;
  padding-left: 8px;
  border-left: 4px solid #1890ff;
  color: #333;
}

/* 题型区块间隔 */
.question-type-section {
  margin-bottom: 24px;
}

/* 题型统计 */
.exercise-stats {
  margin-bottom: 25px;
}

.stats-card {
  background-color: #f9f9f9;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 15px;
}

.stats-content {
  display: flex;
  justify-content: center;
  flex-wrap: wrap;
  gap: 15px 30px;
}

.stat-item {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.stat-label {
  font-weight: bold;
  color: #333;
}

.stat-value {
  margin-left: 5px;
}

/* 题目列表 */
.exercises-list {
  margin-bottom: 30px;
}

.exercise-item {
  margin-bottom: 25px;
}

.exercise-card {
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 20px;
}

.exercise-content {
  /* padding: 30px; */
}

.exercise-title {
  font-size: 16px;
  margin-bottom: 15px;
  /* display: flex;
  align-items: baseline; */
  line-height: 1.6;
  color: #333;
}

.answer-textarea{
   resize: none; /* 禁用手动调整大小 */
  min-height: 100px;
  overflow-y: hidden; /* 隐藏滚动条 */
}

.exercise-number {
  font-weight: bold;
  margin-right: 8px;
  color: #333;
}

.exercise-text {
  flex: 1;
}

.exercise-score {
  color: #333;
  margin-left: 10px;
  font-weight: bold;
}

.question-title{
  display: flex;       /* 启用 Flex 布局 */
  align-items: center; /* 垂直居中对齐 */
  gap: 0;             /* 子元素之间无间距 */
}

.question-order,
.question-texts,
.question-score {
  margin: 0;          /* 移除默认外边距 */
  padding: 0;         /* 移除默认内边距 */
  white-space: nowrap; /* 防止换行 */
}

/* 选择题样式 */
.exercise-options {
  margin-left: 25px;
}

.options-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.option-item {
  display: flex;
  align-items: center;
}

.option-radio {
  margin-right: 10px;
}

.option-label {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.option-letter {
  font-weight: bold;
  margin-right: 8px;
  color: #333;
}

.option-text {
  color: #333;
}

/* 填空题样式 */
.exercise-fill {
  margin-top: 15px;
}

.fill-input {
  /* 基础样式 */
  min-width: 120px;
  width: 100%;
  padding: 8px 12px;
  font-size: 16px;
  line-height: 1.5;
  color: #333;
  background-color: #fff;
  
  /* 边框设计 */
  border: 2px solid #d1d5db;
  border-radius: 6px;
  outline: none;
  
  /* 过渡效果 */
  transition: all 0.3s ease;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

/* 聚焦状态 */
.fill-input:focus {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.2);
}


/* 暗色模式适配 */
@media (prefers-color-scheme: dark) {
  .fill-input {
    background-color: #1f2937;
    border-color: #4b5563;
    color: #f3f4f6;
  }
  
  .fill-input:focus {
    border-color: #60a5fa;
    box-shadow: 0 0 0 3px rgba(96, 165, 250, 0.3);
  }
}

/* 强调版本 */
.fill-input.emphasized {
  border-bottom: 3px solid #3b82f6;
  border-radius: 0;
  padding-bottom: 6px;
  background: transparent;
  border-top: none;
  border-left: none;
  border-right: none;
}

/* 判断题样式 */
.exercise-judge {
  margin-top: 15px;
  margin-left: 25px;
}

.judge-group {
  display: flex;
  gap: 20px;
}

.judge-item {
  display: flex;
  align-items: center;
}

.judge-radio {
  margin-right: 8px;
}

.judge-label {
  cursor: pointer;
}

/* 简答题样式 */
.exercise-short-answer {
  margin-top: 15px;
}

.answer-textarea {
  width: 100%;
  min-height: 100px;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-family: "SimHei", "Microsoft YaHei", sans-serif;
  font-size: 14px;
  line-height: 1.5;
}

.answer-textarea:focus {
  outline: none;
  border-color: #409eff;
}

/* 答案和解析 */
.exercise-result {
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px dashed #ddd;
  border-bottom: 1px dashed #ddd ;
  margin-bottom: 20px;
  padding-bottom: 15px;
  /* border-radius: 5%; */
}

.exercise-result-answer{
  display: flex;
}

.exercise-result-label{
  width: 10%;
  /* height: 200px; */
}

.exercise-result-answer-text{
  width: 90%;
}

.result-item {
  margin-bottom: 8px;
  font-size: 14px;
  display: flex;
}

.questionContentsAnalysis{
  display: flex;
}

.result-label {
  font-weight: bold;
  color: #333;
  min-width: 70px;
}

.result-value {
  flex: 1;
}

.result-value.correct {
  color: #67c23a;
}

.result-value.wrong {
  color: #f56c6c;
}

/* 操作按钮 */
.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}

.save-btn, .submit-btn {
  width: 120px;
  height: 40px;
  font-size: 15px;
  letter-spacing: 1px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-family: "SimHei", "Microsoft YaHei", sans-serif;
}

.save-btn {
  background-color: #409eff;
  color: white;
}

.save-btn:hover {
  background-color: #66b1ff;
}

.submit-btn {
  background-color: #67c23a;
  color: white;
}

.submit-btn:hover {
  background-color: #85ce61;
}

/** 右边操作设置 */
/* 图片容器（右侧） */
.left-container {
  width: 400px;
  padding: 20px;
  margin: 0px 20px;
  background-color: #f5f5f5;
  /* box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); */
  border: 1px solid #ddd;
  /* display: flex;
  align-items: flex-start;
  justify-content: center; */
}


.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 20px;
}

.action-btn {
  padding: 6px 12px;
  background-color: #f5f5f5;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  color: #333;
  transition: all 0.3s;
}

.action-btn:hover {
  background-color: #e6e6e6;
  border-color: #c0c0c0;
}


.stats-info {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 15px;
  font-size: 14px;
  color: #666;
}

.stats-divider {
  color: #d9d9d9;
}

.exercise-type-stats {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.type-item {
  border: 1px solid #f0f0f0;
  border-radius: 4px;
  padding: 10px;
}

.type-header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 8px;
  font-size: 14px;
}

.type-count, .type-percent {
  color: #666;
  font-size: 13px;
}

.exercise-numbers {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.exercise-numbers span {
  display: inline-block;
  width: 24px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  background-color: #f5f5f5;
  border-radius: 4px;
  font-size: 13px;
}

</style>